package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    //查询所有用户信息
    @Override
    public List<User> findAll() {

        return userDao.findAll();
    }


    //分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        log.info("------UserServiceImpl------pageQuery------传递到实现类的分页参数------当前" + currentPage + "页," + "每页展示" + pageSize + "条," + "查询条件为:" + queryString);
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findByCondition(queryString);
        log.info("------UserServiceImpl------pageQuery------查询到的分页对象信息page------" + page);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public Integer[] selectedRoleId(Integer id) {
        return userDao.findRoleAssociationIds(id);
    }

    @Transactional
    @Override
    public void add(User user, Integer[] roleIds) {
        //保存用户基本信息
        userDao.add(user);
        //保存用户关联角色数据
        if (roleIds != null) {
            setRoleAssociation(user.getId(), roleIds);
        }
    }

    @Transactional
    @Override
    public void deleteById(Integer id) {
        //删除关联关系
        userDao.deleteRoleAssociation(id);
        //删除用户
        userDao.deleteById(id);
    }

    //更新用户信息
    @Transactional
    @Override
    public void update(User user, Integer[] roleIds) {
        userDao.update(user);
        //删除之前用户和与角色的关联信息
        userDao.deleteRoleAssociation(user.getId());
        //保存新的用户和与角色的关联信息
        if (roleIds != null) {
            setRoleAssociation(user.getId(), roleIds);
        }
    }


    //保存用户和角色的关联信息
    private void setRoleAssociation(Integer userId, Integer[] roleIds) {
        Stream.of(roleIds).forEach(roleId -> userDao.setRoleAssociation(userId, roleId));
    }
}
